/*
 * Copyright (C) 2007, CERTI Foundation
 * Portions Copyright (C) 2005 Sam Stephenson <sam@conio.net>
 * Portions Copyright (C) 2005 ILOG http://www.ilog.fr
 * Portions Copyright (C) 2004 Damien Mandrioli and Romain Raugi
 * Portions Copyright (C) 2003-2004 Kupu Contributors. All rights reserved.
 *  
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *  
 */


function AdvancedEditor(id) {
	this.id = id;

	this.show = function() {
		new Lightbox.base(id);
	};

	this.hide = function() {
		Lightbox.hideAll();
	};
	
	this.setContents = function(text) {
		document.getElementById('textarea-advanced-editor').value= charRefToUnicode(text);
	}
	
	this.getContents = function() {
		return document.getElementById('textarea-advanced-editor').value;
	}
}

function changeToAdvancedEditor() {
	var url = getKupu().config.url_path+'/edit/'+getKupu().config.current_web+'/'+getKupu().config.current_topic;
	var params = 'skin=kupuxml&wysiwyg_edit=1&text=';
	kupu = getKupu();
	
	//resize textarea according to the size of the window
	resizeElement("textarea-advanced-editor");
	
	prepareSubmitAndSuspendBasicEditor( url , params, onReadyStateAdvancedEditor);
}

function resizeElement(id) {
	var height=window.innerWidth;//Firefox
	if (document.body.clientHeight)	{
		height=document.body.clientHeight;//IE
	}
	document.getElementById(id).style.height=parseInt(height-100-document.getElementById(id).offsetTop-8)+"px";
}

function cancelAdvancedEditor() {
  kupu = getKupu();
  editor.hide();
  kupu.resumeEditing();
}

function saveAndCloseAdvancedEditor() {
 var form = getFromSelector('twiki-main-form');

 //remove wysiwyg_edit so save will not try to convert HTML to TML
 form.elements['wysiwyg_edit'].value = '0'; 
   
  
 //append content
 var contents =  editor.getContents();
 var ta = document.createElement('textarea');
 ta.style.visibility = 'hidden';
 var text = document.createTextNode(contents);
 ta.appendChild(text);
 ta.setAttribute('name', 'text');
 form.appendChild(ta);
   
 form.elements['action_save'].value = 'foobar';
 form.submit();
  
}

function saveAdvancedEditor() {
	var urlChangeToBasicEditor = getKupu().config.url_path+'/save/'+getKupu().config.current_web+'/'+getKupu().config.current_topic;
	var paramsChangeToBasicEditor = 'text=';
	
	var contents =  editor.getContents();
	var parameters = paramsChangeToBasicEditor+url_encode(contents);
	sendRequest('POST', urlChangeToBasicEditor , parameters, onReadyStateSaveAdvanced);
}

function onReadyStateSaveAdvanced() {
    var ready = req.readyState;
    if (ready == 4) {
		if (req.status == 200) {
			document.getElementById('div_loading').innerHTML= '';
       	} else {
			document.getElementById('div_loading').innerHTML= '';
			alert('Server error');
       	}
    } else {
		var data="&nbsp;Loading...&nbsp;";
		var conteudo=document.getElementById('div_loading');
		conteudo.innerHTML=data;
    }
}

function getKupu() {
 if (!kupu) {
    // nasty hack, but I don't know how else to do it
    kupu = window.drawertool.editor;
  }
  return kupu;
}

function changeToBasicEditor() {
	var urlChangeToBasicEditor = getKupu().config.url_path+'/view/'+getKupu().config.current_web+'/'+getKupu().config.current_topic;
	var paramsChangeToBasicEditor = 'skin=kupuxml&wysiwyg_edit=1&text=';
	
	var contents =  editor.getContents();
	var parameters = paramsChangeToBasicEditor+url_encode(contents);
	sendRequest('POST', urlChangeToBasicEditor , parameters, onReadyStateBasicEditor);
}


function openPreview() {
	var url = getKupu().config.url_path+'/save/'+getKupu().config.current_web+'/'+getKupu().config.current_topic;
	var params = 'action_preview=1&skin=kupuxml&wysiwyg_edit=1&text=';
	
	resizeElement("preview");
	
	prepareSubmitAndSuspendBasicEditor( url , params, onReadyStatePreview);
	
}

function prepareSubmitAndSuspendBasicEditor(url, params, onReadyState) {
	kupu = getKupu();
    var form = getFromSelector('twiki-main-form');
    prepareFormSubmit(kupu, form);
    
	var contents =  form.lastChild.value;
	var parameters = params+url_encode(contents);
	sendRequest('POST', url , parameters, onReadyState);
	
	//save only works with this setting
	kupu._initialized = true;
	//remove input text to permit new generation in next submit
	form.removeChild(form.lastChild);
	//suspend editing until advanced editor loads
	kupu.suspendEditing();
}

function onReadyStatePreview() {
    var ready = req.readyState;
    if (ready == 4) {
		if (req.status == 200) {
			document.getElementById('div_loading').innerHTML= '';
	        document.getElementById('preview').innerHTML= req.responseText;
	       	new Lightbox.base('dgPreview');
       	} else {
			document.getElementById('div_loading').innerHTML= '';
			alert('Server error');
	       	kupu.resumeEditing();
       	}
    } else {
		var data="&nbsp;Loading...&nbsp;";
		var conteudo=document.getElementById('div_loading');
		conteudo.innerHTML=data;
    }
}

function onReadyStateBasicEditor() {
    var ready = req.readyState;
    if (ready == 4) {
		if (req.status == 200) {
	        window.frames['kupu-editor'].document.body.innerHTML= req.responseText;
	        document.getElementById('div_loading').innerHTML= '';
			editor.hide();
	       	kupu.resumeEditing();
       	} else {
			document.getElementById('div_loading').innerHTML= '';
			alert('Server error');
       	}
    } else {
		var data="&nbsp;Loading...&nbsp;";
		var conteudo=document.getElementById('div_loading');
		conteudo.innerHTML=data;
    }
}

function onReadyStateAdvancedEditor() {
    var ready = req.readyState;
    if (ready == 4) {
		if (req.status == 200) {
	        editor.setContents(req.responseText);
	        document.getElementById('div_loading').innerHTML= '';
		    editor.show();
       	} else {
			alert('Server error');
			document.getElementById('div_loading').innerHTML= '';
	       	kupu.resumeEditing();
       	}
    } else {
		var data="&nbsp;Loading...&nbsp;";
		var conteudo=document.getElementById('div_loading');
		conteudo.innerHTML=data;
    }
}

function sendRequest(httpMethod, url, parameters, onReadyState) {
    req = HttpRequestObject();
    if (!req) {
      return;
    }
    if (onReadyState) {
	    req.onreadystatechange=onReadyState;
    }
    req.open(httpMethod , url , true);
    req.setRequestHeader("Content-length", parameters.length);
    req.setRequestHeader("Connection", "close");
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded;");
    req.send(parameters);
    return req;
}

function url_encode(str) {
    var hex_chars = "0123456789ABCDEF";
    var noEncode = /^([a-zA-Z0-9\_\-\.])$/;
    var n, strCode, hex1, hex2, strEncode = "";
    for (n = 0; n < str.length; n++) {
        if (noEncode.test(str.charAt(n))) {
            strEncode += str.charAt(n);
        } else {
            strCode = str.charCodeAt(n);
            hex1 = hex_chars.charAt(Math.floor(strCode / 16));
            hex2 = hex_chars.charAt(strCode % 16);
            strEncode += "%" + (hex1 + hex2);
        }
    }
    return strEncode;
}

function url_decode(str) {
    var n, strCode, strDecode = "";
    for (n = 0; n < str.length; n++) {
        if (str.charAt(n) == "%") {
            strCode = str.charAt(n + 1) + str.charAt(n + 2);
            strDecode += String.fromCharCode(parseInt(strCode, 16));
            n += 2;
        } else {
            strDecode += str.charAt(n);
        }
    }
    return strDecode;
}

function charRefToUnicode(text) {
 return text.replace(
      /&#(([0-9]{1,7})|(x[0-9a-f]{1,6}));?/gi,
      function(match, p1, p2, p3, offset, s)
      {
        return String.fromCharCode(p2 || ("0" + p3));
      });
}